
// 199.二叉树的右视图
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        // 层序遍历保留每一层得最后一个节点
        vector<int> ret;
        queue<TreeNode*> q;
        if(root) q.push(root);

        while(q.size())
        {
            int sz = q.size();
            for(int i = 0 ; i < sz ; i++)
            {
                TreeNode* top = q.front();
                q.pop();
                if(top->left) q.push(top->left);
                if(top->right) q.push(top->right);
                if(i == sz - 1) ret.push_back(top->val);
            }
        }
        return ret;
    }
};